#!/usr/bin/env bash

# Compresses PNG files to lower file sizes
# Results are comparable to compressor.io etc.
# License: CC0

# Usage:
#   - Make sure to chmod +x compresspng.sh
#   - compresspng.sh /path/to/somefile.png
#     Result will be saved as: /path/to/compressed_somefile.png

# Ref: http://www.ffnn.nl/pages/articles/media/png-optimization.php

[ -z "$(command -v convert)" ] && echo 'Error: convert binary missing. Please install ImageMagick.' && exit 1
[ -z "$(command -v optipng)" ] && echo 'Error: optipng binary missing. Please install optipng.' && exit 2

_input_dir="$(dirname $1)"
_input_filename="$(basename $1)"

# Convert to indexed color space
convert -quality 0 +dither -colors 256 "$1" "$_input_dir/compressed_${_input_filename}"

# Compress even more with optipng
optipng -zc1-9 -zm1-9 -zs0-2 -f0-5 -out "$_input_dir/compressed_${_input_filename}" "$_input_dir/compressed_${_input_filename}"
